import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { Popconfirm } from 'antd';
import { PauseCircleFilled } from '@ant-design/icons';
import ProgressBar from './ProgressBar';
import { InbizIcon } from '@inbiz/utils';
import { getFileFailedNum, getFilesStatus } from '../../utils/tool';
import { InBizUploadCtx, InBizUploadListCtx } from '../../context';
import { TextWidget, getMessage } from '@inbiz/react';

const ListFloatLayerHeader = () => {
  const { collapsible, uploader, statusEnum } = useContext(InBizUploadCtx);
  const {
    pausable,
    uploadStatus,
    surplusNum,
    visibleFiles,
    isPackUp,
    onUnwindPackUp,
    onDelectAll,
    onResumPausedFiles,
  } = useContext(InBizUploadListCtx);
  const failedNum = getFileFailedNum(visibleFiles, statusEnum.UPLOAD_FAILED);
  // 是否在暂停中
  const [pauseIng, $pauseIng] = useState(false)
  const pauseIngRef = useRef(false);
  const interRef = useRef<any>();
  useEffect(() => {
    const onUploadChunkSuccess = () => {
      if (pauseIngRef.current) {
        pauseIngRef.current = false;
        $pauseIng(false)
      }
    }
    const onStatusChange = (id: string | number, oldStatus: string, status: string) => {
      if (status == statusEnum.PAUSED) {
        pauseIngRef.current = true;
        $pauseIng(true)
        clearTimeout(interRef.current)
        interRef.current = setTimeout(() => {
          $pauseIng(false)
          pauseIngRef.current = false;
        }, 3000)
      }

    }
    const onProgress = () => {
      clearTimeout(interRef.current)
    }
    uploader.on('uploadChunkSuccess', onUploadChunkSuccess);
    uploader.on('complete', onUploadChunkSuccess);
    uploader.on('statusChange', onStatusChange);
    uploader.on('progress', onProgress);
    return () => {
      uploader.off('uploadChunkSuccess', onUploadChunkSuccess);
      uploader.off('complete', onUploadChunkSuccess);
      uploader.off('statusChange', onStatusChange);
      uploader.off('progress', onProgress);
    };
  }, [uploader]);

  const renderStatus = useMemo(() => {
    return (
      <div className='react-fine-uploader-gallery-modal-header-box'>

        {!!failedNum && uploadStatus == 'done' ? <InbizIcon type="icon-ic-jiancecuowu" /> : uploadStatus === 'pause' ? (
          <PauseCircleFilled style={{ color: 'var(--inbiz-color-primary)' }} />
        ) : (
          <InbizIcon
            type={getFilesStatus(uploadStatus)}
            className={uploadStatus === 'loading' ? 'uploading' : ''}
          />
        )}
        <span className="react-fine-uploader-gallery-modal-header-title">
          {uploadStatus === 'loading' || uploadStatus === 'pause' ? (
            <span>
              {uploadStatus === 'pause'
                ? getMessage('inbizUpload.uploadPause')
                : getMessage('inbizUpload.uploading')}
              <span style={{ margin: '0 6px' }}>·</span>
              <span>
                <TextWidget>inbizUpload.beforeSurplus</TextWidget>
                {surplusNum}
                <TextWidget>inbizUpload.afterSurplus</TextWidget>
              </span>
            </span>
          ) : (
            <span>
              <TextWidget>inbizUpload.uploadDone</TextWidget>
              <span style={{ margin: '0 6px' }}>·</span>
              <span>
                <TextWidget>inbizUpload.beforeTotal</TextWidget>
                {visibleFiles?.length}
                <TextWidget>inbizUpload.afterTotal</TextWidget>
              </span>
              <span>
                {failedNum > 0
                  ? `，${getMessage('inbizUpload.beforeFailed')}${failedNum}${getMessage(
                    'inbizUpload.afterFailed',
                  )}`
                  : null}
              </span>
            </span>
          )}
        </span>
      </div>
    );
  }, [uploadStatus, failedNum, surplusNum]);
  const renderAction = useMemo(() => {
    return (
      <div className="react-fine-uploader-gallery-modal-header-action" onClick={e => e.stopPropagation()}>
        {uploadStatus !== 'done' &&
          (pausable ? (
            <InbizIcon
              type="icon-a-zantingsuoyourenwu-hoverzhuangtaishangchuandanceng"
              style={{ fontSize: '24px' }}
              onClick={(e: any) => {
                onResumPausedFiles('pause');
                e.stopPropagation();
              }}
            />
          ) : (
            <InbizIcon
              title={pauseIng ? getMessage('inbizUpload.paused') : ''}
              type="icon-a-jixusuoyourenwushangchuandanceng"
              style={{ fontSize: '24px', cursor: pauseIng ? 'not-allowed' : 'pointer' }}
              onClick={(e: any) => {
                e.stopPropagation();
                if (pauseIngRef.current) {
                  return
                }
                onResumPausedFiles('resum');
              }}
            />
          ))}
        {uploadStatus === 'loading' || uploadStatus === 'pause' ? (
          <Popconfirm
            title={getMessage('inbizUpload.isOutUpload')}
            placement="left"
            okText={getMessage('inbizUpload.ok')}
            cancelText={getMessage('inbizUpload.cancel')}
            onConfirm={(e: any) => {
              onDelectAll();
              e.stopPropagation();
            }}
            onCancel={(e: any) => {
              e.stopPropagation();
            }}
          >
            <InbizIcon
              type="icon-a-quxiaosuoyourenwushangchuandanceng-jiaoshensehovermianbanshi"
              style={{ fontSize: '24px', marginLeft: '15px' }}
              onClick={(e: any) => {
                e.stopPropagation();
              }}
            />
          </Popconfirm>
        ) : (
          <InbizIcon
            type="icon-a-quxiaosuoyourenwushangchuandanceng-jiaoshensehovermianbanshi"
            style={{ fontSize: '24px', marginLeft: '15px' }}
            onClick={(e: any) => {
              onDelectAll();
              e.stopPropagation();
            }}
          />
        )}
      </div>
    );
  }, [uploadStatus, visibleFiles, pauseIng]);
  return (
    <div
      className={
        collapsible
          ? 'react-fine-uploader-gallery-modal-header react-fine-uploader-gallery-modal-header-hover'
          : 'react-fine-uploader-gallery-modal-header'
      }
      onClick={onUnwindPackUp}
    >
      <div className="react-fine-uploader-gallery-modal-header-content">
        {renderStatus}
        {renderAction}
      </div>
      {/* 弹框打开时，不显示总进度条 */}
      <ProgressBar style={{ display: isPackUp ? 'block' : 'none' }} className="react-fine-uploader-gallery-progress-bar" uploader={uploader} />
    </div>
  );
};

export default ListFloatLayerHeader;
